package www.dianbaozu.com.ui.server

import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import androidx.core.view.ViewCompat
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.provider.BaseNodeProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import www.dianbaozu.com.R
import www.wen.com.common.lib.data.entities.ServerGroupEntity
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:
 * @date 2021/9/16 12:09
 */
class ServerListFirstProvider(var ownUserId: String) : BaseNodeProvider() {

    override val itemViewType: Int
        get() = 1

    override val layoutId: Int
        get() = R.layout.item_server_list_first_provider

    override fun convert(helper: BaseViewHolder, item: BaseNode) {
        val entity = item as ServerGroupEntity.Content
        helper.setVisible(R.id.ivAdd, entity.groupType == "0" && (SpUtil.decodeString(KeyHelper.MMKV_ID) == entity.ownUserId))
        helper.setText(R.id.tvServerName, entity.groupName)
        setArrowSpin(helper, item, false)
    }

    override fun convert(helper: BaseViewHolder, item: BaseNode, payloads: List<Any>) {
        for (payload in payloads) {
            if (payload is Int && payload == EXPAND_COLLAPSE_PAYLOAD) {
                // 增量刷新，使用动画变化箭头
                setArrowSpin(helper, item, true)
            }
        }
    }

    private fun setArrowSpin(helper: BaseViewHolder, data: BaseNode, isAnimate: Boolean) {
        val entity = data as ServerGroupEntity.Content
        val imageView = helper.getView<ImageView>(R.id.ivArrow)
        if (entity.isExpanded) {
            if (isAnimate) {
                ViewCompat.animate(imageView).setDuration(200)
                    .setInterpolator(DecelerateInterpolator())
                    .rotation(0f)
                    .start()
            } else {
                imageView.rotation = 0f
            }
        } else {
            if (isAnimate) {
                ViewCompat.animate(imageView).setDuration(200)
                    .setInterpolator(DecelerateInterpolator())
                    .rotation(180f)
                    .start()
            } else {
                imageView.rotation = 180f
            }
        }
    }

    companion object{
        const val EXPAND_COLLAPSE_PAYLOAD = 110
    }

}